package dal

import (
	"go-admin-auth/app/models"
	"go-admin-auth/conn/mysql_conn"
	"go-admin-auth/httpapi/dto"
	"gorm.io/gorm"
	"time"
)

type userDAO struct{}

var (
	UserDAO = &userDAO{}
)

func (d *userDAO) Query(f *dto.UserQueryForm) (*dto.UserQueryRes, error) {
	session := d.newSession()

	var total int64
	var list []models.TUser

	if f.Name != "" {
		session.Where("name like ?", f.Name)
	}

	if f.RealName != "" {
		session.Where("real_name like ?", f.RealName)
	}

	if f.Email != "" {
		session.Where("email = ?", f.Email)
	}

	if f.Phone != "" {
		session.Where("phone = ?", f.Phone)
	}

	if len(f.OrgIdList) > 0 {
		session.Where("org_id in (?)", f.OrgIdList)
	}

	if len(f.OrderBy) > 0 {
		for _, v := range f.OrderBy {
			session.Order(v)
		}
	}

	if err := session.Count(&total).Error; err != nil {
		return nil, err
	}
	if err := session.Limit(f.Limit()).Offset(f.Offset()).Find(&list).Error; err != nil {
		return nil, err
	}

	return &dto.UserQueryRes{Total: total, List: list}, nil
}

func (d *userDAO) GetList(f *dto.UserQueryForm) ([]*models.TUser, error) {
	var results []*models.TUser

	session := d.newSession()

	err := session.Limit(f.Limit()).Offset(f.Offset()).Find(&results).Error
	if err != nil {
		return nil, err
	}
	return results, nil
}

func (d *userDAO) Get(id int) (*models.TUser, error) {
	info := &models.TUser{}
	session := d.newSession()
	if err := session.Where("id= ?", id).First(info).Error; err != nil {
		return nil, err
	}

	return info, nil
}

func (d *userDAO) GetByUsername(username string) (*models.TUser, error) {
	session := d.newSession()
	info := models.TUser{}

	err := session.Where("name = ?", username).First(&info).Error
	if err != nil {
		return nil, err
	}
	return &info, nil
}

func (d *userDAO) GetMulti(idList []int) (map[int]models.TUser, error) {
	var mMap = make(map[int]models.TUser, 0)
	var results []models.TUser

	session := d.newSession()
	query := session.Where("id IN ?", idList)
	err := query.Find(&results).Error
	if err != nil {
		return nil, err
	}
	for _, v := range results {
		mMap[v.Id] = v
	}
	return mMap, nil
}

func (d *userDAO) Insert(m *models.TUser) error {
	session := d.newSession()
	err := session.Create(m).Error
	return err
}

func (d *userDAO) Update(m *models.TUser) error {
	session := d.newSession()
	err := session.Where("id = ?", m.Id).UpdateColumns(m).Error
	return err
}

func (d *userDAO) Delete(id int) error {
	session := d.newSession()
	err := session.Where("id = ?", id).Updates(map[string]interface{}{"is_deleted": 1, "deleted_at": time.Now()}).Error
	return err
}

func (d *userDAO) RealDelete(id int) error {
	session := d.newSession()
	err := session.Where("id = ?", id).Delete(models.TUser{}).Error
	return err
}

func (d *userDAO) newEngine() *gorm.DB {
	return mysql_conn.GetDb()
}

func (d *userDAO) newSession() *gorm.DB {
	return mysql_conn.GetSession().Table("t_user")
}
